
import { _decorator, Component, assetManager, resources, BufferAsset, LabelComponent, Label, Texture2D, SpriteFrame, Sprite, ImageAsset } from 'cc';
const { ccclass, property } = _decorator;


@ccclass('MainScene')
export class MainScene extends Component {

    @property(LabelComponent)
    jsonContentLbl: LabelComponent = null!;

    @property(Sprite)
    sp: Sprite = null!;

    start() {
        this.loadZip("data").then((file: ArrayBuffer) => {
            this.readZipFile(file);
        })
            .catch((err) => {
                console.log(err);
            });
    }

    private loadZip(url: string): Promise<any> {
        return new Promise((resolve, reject) => {
            resources.load(url, BufferAsset, (err, asset) => {
                if (err) return reject(err);
                resolve(asset.buffer());
            })
        });
    }

    private async readZipFile(file: any) {
        //解析zip包
        const data = await JSZip.loadAsync(file);
        console.log(data);

        //解析json文件
        data.file("data/a.json").async("text").then((content: string) => {
            this.jsonContentLbl.string = content;
        })

        //解析图片文件
        data.file("data/Dungeon.png").async("base64").then((buf: string) => {
            let img = new Image();
            img.src = 'data:image/png;base64,' + buf;

            let texture = new Texture2D();

            img.onload = () => {
                texture.reset({
                    width: img.width,
                    height: img.height
                })
                texture.uploadData(img, 0, 0);
                texture.loaded = true;

                let spriteFrame = new SpriteFrame();
                spriteFrame.texture = texture;
                this.sp.spriteFrame = spriteFrame;
            }
        });
    }
}

